package com.enjoy.studyfragment.widget.contact;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.enjoy.studyfragment.R;


/**
 * 搜索组件
 * Created by Administrator on 2018/2/23.
 */

public class SearchView extends LinearLayout {
    //搜索文本
    public SearchEditText search;
    //取消按钮
    public TextView tvClear;

    public SearchView(Context context) {
        this(context,null);
    }

    public SearchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public SearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public void initView(Context context){
        View rootView = LayoutInflater.from(context).inflate(R.layout.item_search_view,this,true);
        search = rootView.findViewById(R.id.search);
        tvClear = rootView.findViewById(R.id.tvClear);

        //文本变化
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if(s.length() > 0){
                    tvClear.setVisibility(VISIBLE);
                }else {
                    tvClear.setVisibility(GONE);
                }
                if(callback != null){
                    callback.result(s.toString());
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        //清空文本
        tvClear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                search.setText("");
                if(callback != null){
                    callback.cancle();
                }
            }
        });
    }

    private ResultCallback callback;

    public void setCallback(ResultCallback callback) {
        this.callback = callback;
    }

    public interface ResultCallback{
        void result(String s);
        void cancle();
    }
}
